package com.ktgj.customer.controller;

import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.customer.common.CardConstant;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.vo.CustomerDetailed;
import com.ktgj.customer.service.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cardCRMPurchase")
public class CardCRMPurchaseController {

    @Autowired
    private ICardCRMPurchaseService cardCRMPurchaseService;
    @Autowired
    private ICardPurchaseService cardPurchaseService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IPointRecordService recordService;
    @Autowired
    private IDepositBusinessService depositBusinessService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICommonReimbursementsService commonReimbursementsService;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private IBusinessOrderService businessOrderService;

    final static Logger log = LoggerFactory.getLogger(CardCRMPurchaseController.class);

    //下单页面基本数据查询
    @PostMapping("queryPurchaseCardData")
    public AjaxResult queryPurchaseCardData() {
        return AjaxResult.success(cardCRMPurchaseService.queryPurchaseCardData());
    }

    //下单页面用户数据查询
    @PostMapping("purchaseQueryCustomerData")
    public AjaxResult purchaseQueryCustomerData(@RequestBody Map<String, String> map) {
        String phone = null;
        if (map.get("phone") != null && !map.get("phone").equals("")){
            phone = map.get("phone");
        }
        Customer customer = customerService.selectCustomerByContractPhoneOnes(phone);
        Map<String, Object> result = new HashMap<>();
        if (customer == null) {
            result.put("msg", "查无此用户");
            return AjaxResult.success(result);
        }

        result.put("customerId", customer.getCustomerId());
        result.put("customerName", customer.getCustomerName());
        result.put("customerIdType", customer.getIdType());
        result.put("customerCertificateNo", customer.getCustCertificateNo());
        result.put("birthday", customer.getBirthday());
        result.put("exchange", CardConstant.EXCHANGE);
        Long aLong;
        try {
            aLong = recordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e) {
            aLong = 0L;
        }
        result.put("points", aLong);
        BigDecimal bLong = depositBusinessService.queyUserDepositBusiness(customer.getCustomerId());
        result.put("depositBusiness", bLong);
        result.put("msg", "success");

        return AjaxResult.success(result);
    }

    //会员发票抬头查询
    @PostMapping("purchaseQueryCommon")
    public AjaxResult purchaseQueryCommon(@RequestBody Map<String, Object> map) {
        return AjaxResult.success(commonReimbursementsService.purchaseQueryCommon(new Long(map.get("customerId").toString())));
    }

    //用户注册
    @PostMapping("/register")
    public AjaxResult register(@RequestBody Customer customer) {
        if (StringHelper.isNullOrEmpty(customer.getCustomerName()) || StringHelper.isNullOrEmpty(customer.getCustCertificateNo()) || StringHelper.isNullOrEmpty(customer.getIdType()) || StringHelper.isNullOrEmpty(customer.getContractPhoneOne())) {
            return AjaxResult.error("会员信息不完整");
        }
        Customer re = loginService.register(customer, null);
        if (re != null)
            return AjaxResult.success("注册成功");
        return AjaxResult.error("注册失败");
    }


    //价格计算接口
    @PostMapping("calculationRemotely")
    public AjaxResult calculationRemotely(@RequestBody Map<String, Object> map) {
        Long cardId = Long.valueOf(map.get("cardId").toString());//卡id
        String years = map.get("years").toString();//购买年限
        Long creditsNum = 0L;//积分数量
        if (map.get("creditsNum") != null)
            creditsNum = Long.valueOf(map.get("creditsNum").toString());//积分数量
        BigDecimal usedDeposit = new BigDecimal(0);//预留款
        if (map.get("usedDeposit") != null)
            usedDeposit = new BigDecimal(map.get("usedDeposit").toString());
        Long couponId = null;//优惠卷id
        if (map.get("couponId") != null)
            couponId = Long.valueOf(map.get("couponId").toString());//优惠卷id

        return AjaxResult.success(cardCRMPurchaseService.calculationRemotely(cardId, years, creditsNum, usedDeposit, couponId));
    }

    //下单接口
    @PostMapping("crmPuyCardOrder")
    @Transactional
    public AjaxResult crmPuyCardOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Employee employee = loginService.getLoginEmployee(request);
        if (employee == null)
            return AjaxResult.error("登录过期");

        String type = map.get("type").toString();

        Customer upd = new Customer();
        upd.setCustomerId(new Long(map.get("customerId").toString()));
        upd.setCustomerName(map.get("customerName").toString());
        upd.setIdType(map.get("idType").toString());
        upd.setCustCertificateNo(map.get("custCertificateNo")==null?"":map.get("custCertificateNo").toString());
        Customer customer = customerService.selectCustomerPhoneById(upd.getCustomerId());
        String phone = map.get("contractPhoneOne").toString();
        if (!phone.equals(customer.getContractPhoneOne()) && !phone.equals(customer.getContractPhoneTow())) {
            upd.setContractPhoneTow(phone);
        }
        customerService.update(upd);//以上为修改购买用户的用户信息


        Map<String, Object> map1 = new HashMap<>();


        String years = map.get("years").toString();//购买年限
        Long cardId = Long.valueOf(map.get("cardId").toString());//卡id
        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
        Long creditsNum = 0L;//积分数量
        if (map.get("creditsNum") != null)
            creditsNum = Long.valueOf(map.get("creditsNum").toString());//积分数量
//        BigDecimal usedDeposit = new BigDecimal(0);//预留款
//        if (map.get("usedDeposit") != null)
//            usedDeposit = new BigDecimal(map.get("usedMoney").toString());
        Long couponId = null;//优惠卷id
        if (map.get("couponId") != null)
            couponId = Long.valueOf(map.get("couponId").toString());//优惠卷id
        BigDecimal couponMoney = new BigDecimal(0);//优惠卷优惠金额
        if (map.get("couponMoney") != null)
            couponMoney = new BigDecimal(map.get("couponMoney").toString());//优惠卷优惠金额


        String invoiceHeadsUp = map.get("invoiceHeadsUp") == null ? null : map.get("invoiceHeadsUp").toString();
        String invoiceType = map.get("invoiceType") == null ? null : map.get("invoiceType").toString();
        String identificationNumber = map.get("identificationNumber") == null ? null : map.get("identificationNumber").toString();
        String registeredAddress = map.get("registeredAddress") == null ? null : map.get("registeredAddress").toString();
        String invoicePhone = map.get("phone") == null ? null : map.get("phone").toString();
        String bankName = map.get("bankName") == null ? null : map.get("bankName").toString();
        String bankAccount = map.get("bankAccount") == null ? null : map.get("bankAccount").toString();
        CommonReimbursements commonReimbursements = new CommonReimbursements();
        commonReimbursements.setInvoiceHeadsUp(invoiceHeadsUp);
        commonReimbursements.setInvoiceType(invoiceType);
        commonReimbursements.setIdentificationNumber(identificationNumber);
        commonReimbursements.setRegisteredAddress(registeredAddress);
        commonReimbursements.setPhone(invoicePhone);
        commonReimbursements.setBankName(bankName);
        commonReimbursements.setBankAccount(bankAccount);

        List<Integer> product = new ArrayList<>();
        if (map.get("products") != null) {
            Object products = map.get("products");
            product = objToList(products, Integer.class);
        }

        if (map.get("otherPhone") != null && !map.get("otherPhone").toString().equals("")) {
            Customer otherUpd = new Customer();
            otherUpd.setCustomerName(map.get("otherCustomerName").toString());
            otherUpd.setIdType(map.get("otherIdType").toString());
            otherUpd.setCustCertificateNo(map.get("otherCustCertificateNo").toString());
            String otherPhone = map.get("otherPhone").toString();

            Customer otherCustomer = customerService.customerPhoneLogin(otherPhone);
            if (otherCustomer == null) {//如果没有此用户，为用户注册
                otherUpd.setContractPhoneOne(otherPhone);
                otherCustomer = loginService.register(otherUpd, null);
                otherUpd.setCustomerId(otherCustomer.getCustomerId());
            } else {//如果有该用户，为该用户修改
                otherUpd.setCustomerId(otherCustomer.getCustomerId());
                Customer re = customerService.selectCustomerPhoneById(otherUpd.getCustomerId());
                if (!otherPhone.equals(re.getContractPhoneOne()) && !otherPhone.equals(re.getContractPhoneTow())) {
                    otherUpd.setContractPhoneTow(otherPhone);
                }
                customerService.update(otherUpd);//以上为修改购买用户的用户信息
            }

            String s;
            try {
                s = cardCRMPurchaseService.buyCardOrder(upd.getCustomerId(), cardId, creditsNum, couponId, usedMoney, couponMoney, years, otherUpd.getCustomerId(), employee.getEmployeeId(), employee.getDeptId(), commonReimbursements, type, product);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            map1.put("OrderNum", s);
            return AjaxResult.success(map1);
        }

        String s;
        try {
            s = cardCRMPurchaseService.buyCardOrder(upd.getCustomerId(), cardId, creditsNum, couponId, usedMoney, couponMoney, years, upd.getCustomerId(), employee.getEmployeeId(), employee.getDeptId(), commonReimbursements, type, product);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        map1.put("OrderNum", s);

        return AjaxResult.success(map1);
    }

    public static <T> List<T> objToList(Object obj, Class<T> cla) {
        List<T> list = new ArrayList<T>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                list.add(cla.cast(o));
            }
            return list;
        }
        return null;
    }

    //CRM购卡无卡无密支付
    @PostMapping("cardCRMPurchaseBankCard")
    public AjaxResult cardCRMPurchaseBankCard(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long bankCardId = Long.valueOf(map.get("bankCardId").toString());
        String orderNum = map.get("orderNum").toString();
        String type = "";
        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount").toString());
        }
        if (map.get("type") != null && !map.get("type").toString().equals(""))
            type = map.get("type").toString();

        String msg;
        try {
            msg = cardCRMPurchaseService.cardCRMPurchaseBankCard(orderNum, bankCardId, request, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(msg);
    }

    //CRM购卡电话语音支付
    @PostMapping("cardCRMPurchaseVoicePay")
    public AjaxResult cardCRMPurchaseVoicePay(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String orderNum = map.get("orderNum").toString();
        String cardNumber = map.get("cardNumber").toString();

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount").toString());
        }
        String type = map.get("type").toString();

        String pay;
        try {
            pay = cardCRMPurchaseService.cardCRMPurchaseVoicePay(orderNum, cardNumber, request, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(pay);
    }

    //CRM购卡银联二维码支付
    @PostMapping("/cardCRMPurchaseGetQRCode")
    public AjaxResult cardCRMPurchaseGetQRCode(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String orderNum = map.get("orderNum").toString();

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount").toString());
        }
        String type = map.get("type").toString();

        UnionPayQRCodeResponseApi unionPayQRCodeResponseApi;
        try {
            unionPayQRCodeResponseApi = cardCRMPurchaseService.cardCRMPurchaseGetQRCode(orderNum, request, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(unionPayQRCodeResponseApi);
    }

    //CRM银联支付二维码关闭在获取
    @PostMapping
    public AjaxResult getBillQRCode(@RequestBody Map<String, Object> map) {
        return AjaxResult.success(businessOrderService.getBillQRCode(map.get("orderNum").toString()));
    }

    //crm总办购卡
    @PostMapping("/cardCRMPurchasePresentCard")
    public AjaxResult cardCRMPurchasePresentCard(@RequestBody Map<String, Object> map)
    {
        try
        {
            String orderNum = map.get("orderNum").toString();
            cardPurchaseService.cardOrderResult(true, orderNum, "", BusinessTypeConstants.PresentPay.getValue());
        } catch (Exception e)
        {
            log.error(e.getMessage());
            return AjaxResult.error("总办赠卡购买失败！");
        }
        return AjaxResult.success("总办赠卡购买成功！");
    }

    //支付完支付回调成功后调用的回调方法
    @PostMapping("getOrderResult")
    public void getOrderResult(@RequestBody Map<String, Object> map) {
        boolean bool = new Boolean(map.get("bool").toString());
        String orderNum = map.get("orderNum").toString();
        String partyPayNum = map.get("partyPayNum").toString();
        String payType = map.get("payType").toString();
        cardPurchaseService.cardOrderResult(bool, orderNum, partyPayNum, payType);
    }

    /**
     * 查询待修改的会员详细信息
     * */
    @PostMapping("/customerDetailed")
    public AjaxResult customerDetailed(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        CustomerDetailed customerDetailed = customerService.customerDetailed(id);
        return AjaxResult.success(customerDetailed);
    }

    /**
     * 修改的会员详细信息
     * */
    @PostMapping("/updateCustomerDetailed")
    public AjaxResult updateCustomerDetailed(@RequestBody CustomerDetailed customerDetailed){
        int i;
        try {
            i = customerService.updateCustomerDetailed(customerDetailed);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (i > 0){
            return AjaxResult.success("修改成功");
        }
        else {
            return AjaxResult.error("修改失败");        }
    }
}
